package com.yuju.controller.pay;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.yuju.cache.RedisCache;
import com.yuju.common.Result;
import com.yuju.constant.CacheKey;
import com.yuju.constant.Constant;
import com.yuju.controller.base.BaseController;
import com.yuju.hotel.model.HotelParamModel;
import com.yuju.hotel.service.IHotelParamService;
import com.yuju.pay.service.IAlipayService;
import com.yuju.util.ConfigUtil;
import com.yuju.util.Utils;

/**
 * 
 * 类名：AlipayController  <br />
 *
 * 功能：支付宝接口
 *
 * @author : xuehj <br />
 * @Date : 2018年2月2日 下午1:50:46  <br />
 * @version : 1.1 <br />
 */
@Controller
@RequestMapping("alipay")
public class AlipayController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);
	private RedisCache<String, String> redisCache = RedisCache.getInstance();
	
	@Autowired
	private IHotelParamService hotelParamService;
	@Autowired
	private IAlipayService aliPayService;
	@RequestMapping("callback")
	public void alipayCallback() {
		System.out.println("支付宝回调接口");
		String appAuthCode = getRequest().getParameter("app_auth_code");
		// 判断是否商户授权
		if (Utils.isNotNull(appAuthCode)) {
			updateAppAutoToken(appAuthCode);
		} else {
			String body = getRequest().getParameter("body");
			String out_trade_no = getRequest().getParameter("out_trade_no");
			String trade_status = getRequest().getParameter("trade_status");
			String app_id = getRequest().getParameter("app_id");
			String total_amount = getRequest().getParameter("total_amount");
			String buyer_id = getRequest().getParameter("buyer_id");
			String trade_no = getRequest().getParameter("trade_no");
			String open_id = getRequest().getParameter("open_id");
			String buyer_logon_id = getRequest().getParameter("buyer_logon_id");
			String memuuid = getRequest().getParameter("memuuid");
			String memcode = getRequest().getParameter("memcode");
			System.out.println(out_trade_no);
			System.out.println(trade_status);
			if ("TRADE_SUCCESS".equals(trade_status)) {
				System.out.println("支付成功");
			} else {
				System.out.println("支付失败");
			}
		}
	}
	
	/**
	 * 
	 * 功能：更新商户授权的Token<br/>
	 *
	 * @author xuehj
	 * @Date 2018年2月2日 下午2:52:21 <br/>
	 */
	public void updateAppAutoToken(String appAuthCode) {
		ConfigUtil.init("zfbinfo.properties");
		String appId = redisCache.get(Constant.ALIPAY_APPID + CacheKey.KEY_SYS_PARAM);//ConfigUtil.get("appid");
		String appPrivateKey = redisCache.get(Constant.UNIVERSAL_PRIVATE_KEY + CacheKey.KEY_SYS_PARAM); //ConfigUtil.get("private_key");
		String alipayPublicKey = redisCache.get(Constant.ALIPAY_PUBLIC_KEY + CacheKey.KEY_SYS_PARAM);//ConfigUtil.get("alipay_public_key");
		String alipayOpenApiDomainUrl = redisCache.get(Constant.OPEN_API_DOMAIN + CacheKey.KEY_SYS_PARAM);//"https://openapi.alipay.com/gateway.do";
		String signType = redisCache.get(Constant.SIGN_TYPE + CacheKey.KEY_SYS_PARAM);//"RSA2";
		logger.debug("AppID:{}", appId);
		logger.debug("AppPrivateKey:{}", appPrivateKey);
		logger.debug("AlipayPublicKey:{}", alipayPublicKey);
		logger.debug("alipayOpenApiDomainUrl:{}",alipayOpenApiDomainUrl);
		AlipayClient alipayClient = new DefaultAlipayClient(alipayOpenApiDomainUrl, appId, appPrivateKey, "json", "utf-8", alipayPublicKey, signType);
		AlipayOpenAuthTokenAppRequest request = new AlipayOpenAuthTokenAppRequest();
		request.setBizContent("{" +
		"    \"grant_type\":\"authorization_code\"," +
		"    \"code\":\""+ appAuthCode +"\"" +
		"  }");
		try {
			AlipayOpenAuthTokenAppResponse response = alipayClient.execute(request);
			String appAutoToken = response.getAppAuthToken();
			String appRefreshToken = response.getAppRefreshToken();
			logger.debug("商户授权认证Token：" + appAuthCode);
			logger.debug("授权商户PID：" + response.getUserId());
			logger.debug("商户授权认证RefreshToken：" + appRefreshToken);
			logger.debug("商户授权认证Token：" + appAutoToken);
			// 更新酒店对应商户认证令牌
			String hotelId = redisCache.get(response.getUserId() + CacheKey.KEY_HOT_PARAM);
			logger.debug("酒店ID：" + hotelId);
			redisCache.addCache(hotelId + Constant.ALIPAY_APP_AUTH_TOKEN + CacheKey.KEY_HOT_PARAM, appAutoToken);
			redisCache.addCache(hotelId + Constant.ALIPAY_APP_REFRESH_TOKEN + CacheKey.KEY_HOT_PARAM, appRefreshToken);
			
			// 更新酒店参数
			HotelParamModel hotelModel = new HotelParamModel();
			hotelModel.setHotelId(hotelId);
			hotelModel.setCode(Constant.ALIPAY_APP_AUTH_TOKEN);
			hotelModel.setValue(appAutoToken);
			
			hotelParamService.updateSelective(hotelModel);
			
			hotelModel.setCode(Constant.ALIPAY_APP_REFRESH_TOKEN);
			hotelModel.setValue(appRefreshToken);
			
			hotelParamService.updateSelective(hotelModel);
		} catch (AlipayApiException e) {
			logger.error("更新商户授权Token错误：", e);
		}
	}
	/**
	 * 
	 * 功能：支付<br/>
	 *
	 * @author zhousc
	 * @Date 2018年2月6日 下午2:38:58 <br/>
	 */
	@RequestMapping("pay")
	@ResponseBody
	public Result pay(@RequestBody JSONObject obj) {
		//订单号
		String outTradeNo = obj.getString("outTradeNo");
		//分店名
		String hotelName = obj.getString("hotelName");
		//金额
		String totalAmount = obj.getString("totalAmount");
		//付款碼
		String authCode = obj.getString("authCode");
		//收款明细
		String body = obj.getString("body");
		//缓存中取该分店的授权令牌
		String appAuthToken = redisCache.get(obj.getString("storeId") + Constant.ALIPAY_APP_AUTH_TOKEN + CacheKey.KEY_HOT_PARAM);
		//操作员ID
		String operatorId = obj.getString("operatorId");
		//分店ID
		String storeId = obj.getString("storeId");
		//缓存中取ISV服务商的PID
		String providerId = redisCache.get(Constant.PARTNER_ID + CacheKey.KEY_SYS_PARAM);
		
		Result result = aliPayService.pay(outTradeNo, hotelName, totalAmount, authCode, body, appAuthToken, operatorId, storeId, providerId);
		
		return result;
	}
	
	
	@RequestMapping("refund")
	@ResponseBody
	public Result refund(@RequestBody JSONObject obj) {
		//订单号
		String outTradeNo = obj.getString("outTradeNo");
		//退款金额
		String refundAmount = obj.getString("refundAmount"); 
		//退款原因
		String refundReason = obj.getString("refundReason");
		//分店ID
		String storeId = obj.getString("storeId");
		//缓存中取该分店的授权令牌
		String appAuthToken = redisCache.get(obj.getString("storeId") + Constant.ALIPAY_APP_AUTH_TOKEN + CacheKey.KEY_HOT_PARAM);
		
		Result result = aliPayService.refund(outTradeNo, refundAmount, refundReason, storeId ,appAuthToken);
		
		return result;
		
	}
}
